/*
 * timer.h
 *
 *  Created on: 2016年3月2日
 *      Author: Administrator
 */

#ifndef EYAS_SOURCES_TIMER_TIMER_H_
#define EYAS_SOURCES_TIMER_TIMER_H_

#include <boost/noncopyable.hpp>
#include <boost/thread/detail/move.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include "thread/task/thread_task.hpp"
#include "gc/gc.h"
#include "conf/def.h"

namespace eyas {
namespace process {
class processor;
class timer : public boost::noncopyable, public boost::enable_shared_from_this<timer>{
public:
	virtual ~timer();
private:
	boost::asio::deadline_timer timer_;
	int delay_;
	int period_;
	bool enablePeriod_;
	eyas::thread::thread_task_ptr taskPtr_;

	bool enable_;
	boost::recursive_mutex mutex_;
private:
	void release();
	void schedule_timer_task_from_constructor(eyas::thread::thread_task_ptr& taskPtr);
	void schedule_timer_task(eyas::thread::thread_task_ptr& taskPtr);
	void on_timer();

public:
	// 定时任务
	template<typename F, typename... Args>
	timer(F timerfunc, Args... args);

	// 定时任务，仅执行一次
	// delay：开始执行时，延期执行
	void start(int delay);
	// 定时任务，执行多次，使用cancel来取消定时器任务
	// delay：开始执行时，延期执行
	// period：重复固定间隔时间
	void start(int delay, int period);
	// 取消定时器
	void cancel();
};
typedef boost::shared_ptr<timer> timer_ptr;

template<typename F, typename... Args>
timer::timer(F timerfunc, Args... args)
:timer_(eyas::thread::service::instance()->io_service())
, delay_(0), period_(0), enablePeriod_(false), taskPtr_(nullptr), enable_(false){
	eyas::thread::thread_task_ptr task_ptr = eyas::gc::create_new<eyas::thread::thread_task<F>>(boost::bind(timerfunc, args...));
	BOOST_ASSERT(task_ptr);

	this->delay_ = 0;
	this->period_ = 0;
	this->enablePeriod_ = false;
	this->schedule_timer_task_from_constructor(task_ptr);
}

} /* namespace timer */
} /* namespace eyas */

#endif /* EYAS_SOURCES_TIMER_TIMER_H_ */
